//
//  RequestApi+Home.swift
//  接口请求- 首页
//
//  Created by 千策万划-mini on 2025/4/30.
//

import CoreTelephony
import Foundation
import UIKit
import CoreLocation

class HomeRequestApi: RequestApi {

    // MARK: - APP首页
    class func home(
        success: @escaping RequestSuccess, failure: @escaping RequestFailure
    ) {
        var parameters: [String: Any]? {
            return [
                "sank": GlobalMethod.getConfusion(),
                "teach": GlobalMethod.getConfusion(),
            ]
        }
        get(path: ApiConfig.home, parameters: parameters, success: success, failure: failure)
    }

    // MARK: - 点击申请
    class func productApply(
        productCode: String,
        success: @escaping RequestSuccess, failure: @escaping RequestFailure
    ) {
        var parameters: [String: Any]? {
            return [
                "carry": productCode,
                "starving": GlobalMethod.getConfusion(),
                "shell": GlobalMethod.getConfusion(),
            ]
        }
        post(path: ApiConfig.productApply, parameters: parameters, success: success, failure: failure)
    }

    // MARK: - 产品详情
    class func productDetail(
        productCode: String,
        delegate _: AnyObject? = nil,
        success: @escaping RequestSuccess, failure: @escaping RequestFailure
    ) {
        var parameters: [String: Any]? {
            return [
                "carry": productCode,
                "nut": GlobalMethod.getConfusion(),
                "hit": GlobalMethod.getConfusion(),
            ]
        }
        post(path: ApiConfig.productDetail, parameters: parameters, success: success, failure: failure)
    }

    // MARK: - 获取用户身份信息（第一项）
    class func getUserIdentityInfoOneItem(
        productCode: String,
        success: @escaping RequestSuccess, failure: @escaping RequestFailure
    ) {
        var parameters: [String: Any]? {
            return [
                "carry": productCode,
                "cage": GlobalMethod.getConfusion(),
            ]
        }
        get(path: ApiConfig.getUserIdentityInfoOneItem, parameters: parameters, success: success, failure: failure)
    }

    // MARK: - 接口上传(face,身份证正面)（第一项）
    class func uploadImage(
        shed: String, // 图片来源:1相册 2:拍照上传
        carry: String, // 产品id
        wisest: String, // 10:人脸自拍, 11身份证正面
        image: UIImage,
        rag: String, // 卡类型
        success: @escaping RequestSuccess, failure: @escaping RequestFailure
    ) {
        // 压缩图片
        guard let data = image.jpegData(compressionQuality: 0.8) else {
            return
        }
        var imageData = data
        if data.count > 500 * 1024 {
            var compressionQuality: CGFloat = 0.8
            while imageData.count > 500 * 1024 && compressionQuality > 0.1 {
                compressionQuality -= 0.1
                if let newData = image.jpegData(compressionQuality: compressionQuality) {
                    imageData = newData
                }
            }
        }
        var parameters: [String: Any]? {
            return [
                "shed": UnPackStr(shed),
                "carry": UnPackStr(carry),
                "wisest": UnPackStr(wisest),
                "rag": UnPackStr(rag),
                "necessary": "",
                "bade": GlobalMethod.getConfusion(),
                "tighter": "1",
            ]
        }
        upload(path: ApiConfig.uploadImage, method: .post, parameters: nil, multipartFormData: { formData in
            // 添加图片文件
            formData.append(imageData, withName: "sulked", fileName: "image.jpg", mimeType: "image/jpeg")
            // 添加其他参数
            for (key, value) in parameters ?? [:] {
                if let str = value as? String, let data = str.data(using: .utf8) {
                    formData.append(data, withName: key)
                }
            }
        }, success: success, failure: failure)
    }

    // MARK: - 保存用户身份证信息（第一项）
    class func saveUserIdentityInfoOneItem(
        birth: String,
        number: String,
        name: String,
        cardType: String,
        success: @escaping RequestSuccess, failure: @escaping RequestFailure
    ) {
        var parameters: [String: Any]? {
            return [
                "stubby": UnPackStr(birth),
                "half": UnPackStr(number),
                "cautiously": UnPackStr(name),
                "wisest": "11",
                "rag": UnPackStr(cardType),
                "glove": GlobalMethod.getConfusion(),
            ]
        }
        post(path: ApiConfig.saveUserIdentityInfoOneItem, parameters: parameters, success: success, failure: failure)
    }

    // MARK: - 获取用户身份信息（第二项）
    class func getUserIdentityInfoTwoItem(
        productCode: String,
        success: @escaping RequestSuccess, failure: @escaping RequestFailure
    ) {
        var parameters: [String: Any]? {
            return [
                "carry": productCode,
            ]
        }
        post(path: ApiConfig.getUserIdentityInfoTwoItem, parameters: parameters, success: success, failure: failure)
    }

    // MARK: - 地址初始化
    class func getCityList(
        success: @escaping RequestSuccess, failure: @escaping RequestFailure
    ) {
        get(path: ApiConfig.getCityList, parameters: nil, success: success, failure: failure)
    }

    // MARK: - 保存用户身份证信息（第二项）
    class func saveUserIdentityInfoTwoItem(
        parameters: [String: Any],
        success: @escaping RequestSuccess, failure: @escaping RequestFailure
    ) {
        post(path: ApiConfig.saveUserIdentityInfoTwoItem, parameters: parameters, success: success, failure: failure)
    }

    // MARK: - 获取工作信息（第三项）
    class func getWorkInfoThreeItem(
        productCode: String,
        success: @escaping RequestSuccess, failure: @escaping RequestFailure
    ) {
        var parameters: [String: Any]? {
            return [
                "carry": productCode,
            ]
        }
        post(path: ApiConfig.getWorkInfoThreeItem, parameters: parameters, success: success, failure: failure)
    }

    // MARK: - 保存工作信息（第三项）
    class func saveWorkInfoThreeItem(
        parameters: [String: Any],
        success: @escaping RequestSuccess, failure: @escaping RequestFailure
    ) {
        post(path: ApiConfig.saveWorkInfoThreeItem, parameters: parameters, success: success, failure: failure)
    }

    // MARK: - 获取联系人信息第四项
    class func getContactInfoFourItem(
        productCode: String,
        success: @escaping RequestSuccess, failure: @escaping RequestFailure
    ) {
        var parameters: [String: Any]? {
            return [
                "carry": productCode,
                "pitying": GlobalMethod.getConfusion(),
            ]
        }
        post(path: ApiConfig.getContactInfoFourItem, parameters: parameters, success: success, failure: failure)
    }

    // MARK: - 保存联系人信息第四项
    class func saveContactInfoFourItem(
        parameters: [String: Any],
        success: @escaping RequestSuccess, failure: @escaping RequestFailure
    ) {
        post(path: ApiConfig.saveContactInfoFourItem, parameters: parameters, success: success, failure: failure)
    }

    // MARK: - 获取绑卡信息（第五项）
    class func getBankCardInfoFiveItem(
        success: @escaping RequestSuccess, failure: @escaping RequestFailure
    ) {
        var parameters: [String: Any]? {
            return [
                "weeniest": "0",
                "teeniest": GlobalMethod.getConfusion(),
            ]
        }
        post(path: ApiConfig.getBankCardInfoFiveItem, parameters: parameters, success: success, failure: failure)
    }

    // MARK: - 提交绑卡（第五项）
    class func saveBankCardInfoFiveItem(
        parameters: [String: Any],
        success: @escaping RequestSuccess, failure: @escaping RequestFailure
    ) {
        post(path: ApiConfig.saveBankCardInfoFiveItem, parameters: parameters, success: success, failure: failure)
    }

    // MARK: - 跟进订单号获取跳转地址
    class func getJumpAddress(
        orderCode: String,
        success: @escaping RequestSuccess, failure: @escaping RequestFailure
    ) {
        var parameters: [String: Any]? {
            return [
                "rascal": UnPackStr(orderCode),
                "poured": GlobalMethod.getConfusion(),
                "flood": GlobalMethod.getConfusion(),
                "swung": GlobalMethod.getConfusion(),
                "cruelly": GlobalMethod.getConfusion(),
            ]
        }
        post(path: ApiConfig.getJumpAddress, parameters: parameters, success: success, failure: failure)
    }

    // MARK: - 订单列表
    class func orderList(
        orderState: String, // 4全部 7进行中 6待还款 5已结清
        delegate: AnyObject? = nil,
        success: @escaping RequestSuccess, failure: @escaping RequestFailure
    ) {
        var parameters: [String: Any]? {
            return [
                "savagely": UnPackStr(orderState),
            ]
        }
        post(path: ApiConfig.orderList, parameters: parameters, delegate: delegate, success: success, failure: failure)
    }
    
    // MARK: - google_market上报(并返回facebook配置)
    class func getFaceBookConfig(
        delegate: AnyObject? = nil,
        success: @escaping RequestSuccess, failure: @escaping RequestFailure
    ) {
        let idfv = KeychainHelper.getIDFVFromKeychain()
        GlobalMethod.getIDFA()
        let idfa = GlobalMethod.readUnprefixedStrFromUserDefaults(forKey: LOCAL_IDFA)
        var parameters: [String: Any]? {
            return [
                "cruelly":  GlobalMethod.getConfusion(),
                "meddling": idfv,   //idfv
                "wire":     idfa    //idfa
            ]
        }
        post(path: ApiConfig.getFaceBookConfig, parameters: parameters, showToast: false, isShowLoading: false, delegate: delegate, success: success, failure: failure)
    }

    // MARK: - 埋点
    class func buryPoint(
        productCode: String,
        type: String,
        startTime: String,
        endTime: String,
        delegate: AnyObject? = nil,
        success: @escaping RequestSuccess, failure: @escaping RequestFailure
    ) {
        let locationFetcher = LocationFetcher()
        locationFetcher.fetchLocation { coordinate in
            //print("获取到位置：纬度 \(coordinate.latitude), 经度 \(coordinate.longitude)")
            // LocationService.shared.startUpdatingLocation()
            
            let idfv = KeychainHelper.getIDFVFromKeychain()
            GlobalMethod.getIDFA()
            let idfa = GlobalMethod.readUnprefixedStrFromUserDefaults(forKey: LOCAL_IDFA)

            var parameters: [String: Any]? {
                return [
                    "hark": UnPackStr(productCode),
                    "towards": UnPackStr(type),
                    "hurriedly": "",
                    "steps": UnPackStr(idfv),
                    "move": UnPackStr(idfa),
                    "smells": (coordinate?.longitude ?? ""),
                    "common": (coordinate?.latitude ?? ""),
                    "harmless": UnPackStr(startTime),
                    "smaller": UnPackStr(endTime),
                    "daily": GlobalMethod.getConfusion(),
                ]
            }
            post(path: ApiConfig.buryPoint, parameters: parameters, showToast: false, isShowLoading: false, delegate: delegate, success: success, failure: failure)
        }
    }

    // MARK: - 上报 讯录信息
    class func uploadAddressBook(
        list: [Any],
        delegate: AnyObject? = nil,
        success: @escaping RequestSuccess, failure: @escaping RequestFailure
    ) {
        var jsonStr = ""
        do {
            let data = try JSONSerialization.data(withJSONObject: list, options: [])
            let jsonString = String(data: data, encoding: .utf8) ?? ""
            let jsonData = jsonString.data(using: .utf8) ?? Data()
            let base64String = jsonData.base64EncodedString(options: [])
            jsonStr = base64String
        } catch {
            print("JSON序列化失败: \(error)")
        }
        let parameters: [String: Any] = [
            "wisest": "3",
            "really": GlobalMethod.getConfusion(),
            "crawl": GlobalMethod.getConfusion(),
            "excepting": jsonStr,
        ]
        post(path: ApiConfig.uploadAddressBook, parameters: parameters, showToast: false, isShowLoading: false, delegate: delegate, success: success, failure: failure)
    }

    // MARK: - 上报 设备信息
    class func uploadDeviceInfo(
        delegate: AnyObject? = nil,
        success: @escaping RequestSuccess, failure: @escaping RequestFailure
    ) {
        LocationService.shared.startUpdatingLocation()
        // 获取电池电量百分比
        let device = UIDevice.current
        device.isBatteryMonitoringEnabled = true
        let batteryLevel: Float = device.batteryLevel * 100
        let batteryState = device.batteryState
        device.isBatteryMonitoringEnabled = false  // 获取完后关闭监控
        var simulator = 0
        #if targetEnvironment(simulator)
            // 模拟器
            simulator = 1
        #else
            // 真机
            simulator = 0
        #endif
        // 获取默认语言
        let infoDictionary = Bundle.main.infoDictionary
        let developmentRegion = infoDictionary?["CFBundleDevelopmentRegion"] as? String
        // 默认返回英语，如果没有获取到
        let languageCode = isStr(developmentRegion) ? developmentRegion : "en"
        // 运营商
        let info = CTTelephonyNetworkInfo()
        var mCarrier = ""
        if let carriers = info.serviceSubscriberCellularProviders,
           let carrier = carriers.values.first
        {
            mCarrier = carrier.carrierName ?? ""
        }

        let parameters: [String: Any] = [
            "possessed": "ios",
            "showing": UnPackStr(UIDevice.current.systemVersion),
            "telltale": UnPackStr(GlobalMethod.readStrFromUserDefaults(forKey: LOCAL_LOGIN_SUCCESS_TIME)),
            "ordinary": UnPackStr(GlobalMethod.getBundleName),
            "meddle": [
                "sense": UnPackStr(Int(batteryLevel)),
                "deserved": batteryState == .charging ? "1" : "0",
            ],
            "scrapes": [
                "meddling": UnPackStr(UIDevice.current.identifierForVendor?.uuidString),
                "wire": GlobalMethod.readUnprefixedStrFromUserDefaults(forKey: LOCAL_IDFA),
                "story": UnPackStr(GlobalMethod.getMacBSSID()),
                "wobbly": GlobalMethod.getTimeStampMillisecond(),
                "poking": GlobalMethod.isUsingProxy() ? "1" : "0",
                "forever": GlobalMethod.isVPNConnected() ? "1" : "0",
                "trap": GlobalMethod.isDeviceJailbroken() ? "1" : "0",
                "mouse": UnPackStr(simulator),
                "rat": UnPackStr(languageCode),
                "mice": UnPackStr(mCarrier),
                "rats": GlobalMethod.getNetworkType(),
                "biddies": TimeZone.current.abbreviation() ?? "",
                "shelling": UnPackStr(GlobalMethod.millisecondsSinceBootIncludingSleep()),
            ],
            "simple": [
                "cob": "",
                "handling": "iPhone",
                "hens": "",
                "grain": SCREEN_HEIGHT,
                "dreamed": SCREEN_WIDTH,
                "stripped": UnPackStr(UIDevice.current.name),
                "husk": UnPackStr(GlobalMethod.getDeviceName), // 设备型号 例：iPhone 12 pro max
                "pieces": GlobalMethod.getScreenDiagonalSize(), // 物理尺寸 给 string
                "loveliest": UIDevice.current.systemVersion, // 系统版本
                "raced": UnPackStr(GlobalMethod.getDeviceModel()), // iPhone 原始设备型号
            ],
            "dangerous": [
                "darkest": GlobalMethod.getIPAddress(), // 内网ip
                "eaten": [ // wifi列表  把下面current_wifi放入这个数组即可
                    [
                        "cautiously": UnPackStr(GlobalMethod.getCurrentSSID()), // name
                        "cobs": UnPackStr(GlobalMethod.getMacBSSID()), // bssid
                        "story": UnPackStr(GlobalMethod.getMacBSSID()), // mac
                        "missed": UnPackStr(GlobalMethod.getCurrentSSID()), // ssid
                    ],
                ],
                "crib": [
                    "cautiously": UnPackStr(GlobalMethod.getCurrentSSID()), //  当前的 wifi 名称，传 SSID 即可
                    "cobs": UnPackStr(GlobalMethod.getMacBSSID()), // 当前的 wifi BSSID
                    "story": UnPackStr(GlobalMethod.getMacBSSID()), // 当前的 wifi MAC
                    "missed": UnPackStr(GlobalMethod.getCurrentSSID()), // 当前的 wifi SSID
                ],
                "lesson": 1, // 取上面wifi列表里元素个数 或者 current_wifi有数据就传1
            ],
            "matters": [
                "apple": UnPackStr(GlobalMethod.getNewFreeSizeWithByte()), // 未使用存储大小
                "morrow": UnPackStr(GlobalMethod.totalDiskSpaceInBytes()), // 总存储大小 给int
                "dishonest": UnPackStr(ProcessInfo.processInfo.physicalMemory), // 总内存大小 给int
                "wished": UnPackStr(GlobalMethod.getAvailableMemorySize()), // 未使用内存大小
            ],
        ]
        do {
            let data = try JSONSerialization.data(withJSONObject: parameters, options: [])
            let base64String = data.base64EncodedString(options: [])
            let dict = ["excepting": base64String]
            // print("Base64编码后的字符串: \(base64String)")
            post(path: ApiConfig.uploadDeviceInfo, parameters: dict, showToast: false, isShowLoading: false, delegate: delegate, success: success, failure: failure)
        } catch {
            print("JSON序列化失败: \(error)")
        }
    }

    // MARK: - 上报 位置信息
    class func uploadLocationInfo(
        delegate: AnyObject? = nil,
        success: @escaping RequestSuccess, failure: @escaping RequestFailure
    ) {
        let coordinate = LocationService.shared.getCurrentLocation()
        let lat = String(format: "%.6f", coordinate.latitude)
        let lon = String(format: "%.6f", coordinate.longitude)
        // 进行反向地理编码
        let geocoder = CLGeocoder()
        let location = CLLocation(latitude: coordinate.latitude, longitude: coordinate.longitude)
        geocoder.reverseGeocodeLocation(location) { placemarks, error in
            if error != nil {
                // 未开启手机定位
                let dic: [String: Any] = [
                    "plaything": "", // 省
                    "scary": "", // 国家code
                    "wires": "", // 国家
                    "paw": "", // 街道
                    "common": (lat), // 纬度
                    "smells": (lon), // 经度
                    "smallest": "", // 市
                    "closer": GlobalMethod.getConfusion(), // 混淆字段
                    "appetite": GlobalMethod.getConfusion(), // 混淆字段
                ]
                // 上报
                post(path: ApiConfig.uploadLocationInfo, parameters: dic, showToast: false, isShowLoading: false, delegate: delegate, success: success, failure: failure)
                return
            }
            
            if let placemark = placemarks?.first {
                let province = placemark.administrativeArea ?? "" // 省
                let countryCode = placemark.isoCountryCode ?? "" // 国家code
                let country = placemark.country ?? "" // 国家
                let city = placemark.locality ?? "" // 市
                let district = placemark.subLocality ?? "" // 区
                let dic: [String: Any] = [
                    "plaything": UnPackStr(province), // 省
                    "scary": UnPackStr(countryCode), // 国家code
                    "wires": UnPackStr(country), // 国家
                    "paw": UnPackStr(district), // 街道
                    "common": (lat), // 纬度
                    "smells": (lon), // 经度
                    "smallest": UnPackStr(city), // 市
                    "closer": GlobalMethod.getConfusion(), // 混淆字段
                    "appetite": GlobalMethod.getConfusion(), // 混淆字段
                ]
                // 已开启手机定位
                // 埋点
                if GlobalMethod.readBoolFromUserDefaults(forKey: LOCAL_BURY_POINT_ONE) == false {
                    GlobalMethod.writeBool(true, forKey: LOCAL_BURY_POINT_ONE)
                    GlobalMethod.buryPoint(productCode: "", type: "1", startTime: GlobalMethod.readStrFromUserDefaults(forKey: LOCAL_SMS_SEND_TIME), endTime: GlobalMethod.readStrFromUserDefaults(forKey: LOCAL_LOGIN_SUCCESS_TIME))
                }
                // 上报
                post(path: ApiConfig.uploadLocationInfo, parameters: dic, showToast: false, isShowLoading: false, delegate: delegate, success: success, failure: failure)
            }
        }
    }
}
